<?php
declare (strict_types=1);

namespace app\mall\model\product;

use app\common\model\Attach;
use app\common\model\BaseModel;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * 定义商品数据模型
 */
class Product extends BaseModel
{
    use SoftDelete;

    // 表名
    protected $name = 'mall_product';

    // 设置隐藏字段
    protected $hidden = ['create_time', 'update_time', 'delete_time'];

    protected $type = [
        'fullcategorypath' => 'array',
    ];

    protected $globalScope = ['status'];

    public function scopeStatus($query)
    {
        $query->where('status', 1);
    }

    /**
     * 简介格式转换,防止富文本编辑器中有表情等
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-21
     *
     * @param string $value [description]
     */
    public function setInfoAttr(string $value = ''): string
    {
        return base64_encode($value);
    }

    /**
     * 简介格式转换,防止富文本编辑器中有表情等
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-21
     *
     * @param string $value [description]
     */
    public function getInfoAttr(string $value = '')
    {
        if (!$value) {
            return '';
        }
        if ($value === base64_encode((string)base64_decode($value, true))) {
            return base64_decode($value);
        } else {
            return $value;
        }
    }

    public function coverUrl(): BelongsTo
    {
        return $this->belongsTo(Attach::class, 'cover')->bind(['cover_url' => 'fileurl']);
    }

    public function swiper(): HasMany
    {
        return $this->hasMany(ProductSwiper::class, 'product_id')->field('product_id,attach_id')->with(['attach'])->hidden(['attach_id', 'product_id']);
    }

    public function monthSaleCount(): HasOne
    {
        return $this->hasOne(ProductSaleCount::class, 'product_id')->where('month', date('Ym', time()))->bind(['month_count' => 'count']);
    }
}
